﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using MToolStudio.Render;
using Microsoft.Mtool.FSM;

namespace MToolStudio.UI
{
    public class ActionImplApplyTool : UITool
    {
        private ActionImpl actionImpl;
        private IActionRenderable curFocusAction;
        private ActionTreeViewItemType actionImplType;
        private bool mouseInsideActionListBox;

        public ActionImplApplyTool(FSMDesigner designer, ActionTreeViewItemType type, ActionImpl impl)
            : base(designer)
        {
            actionImpl = impl;
            actionImplType = type;
        }

        public bool MouseInsideActionListBox
        {
            get { return mouseInsideActionListBox; }
            set { mouseInsideActionListBox = value; }
        }

        public override void OnMouseMove(object sender, MouseEventArgs e)
        {
            if (Designer.Cursor != Cursors.PanNE)
                Designer.Cursor = Cursors.PanNE;
            e = TransformToLocal(e);
            foreach (IRenderable item in Designer.RenderItems)
            {
                if (item is IActionRenderable && item.IsSelected(new Point(e.X, e.Y)))
                {
                    if (item as IActionRenderable != curFocusAction)
                    {
                        curFocusAction = item as IActionRenderable;
                        Designer.Refresh();
                    }
                    return;
                }
            }
            curFocusAction = null;
        }

        public override void OnMouseUp(object sender, MouseEventArgs e)
        {
            //if the action treeview item is dragged into the listbox
            if (MouseInsideActionListBox)
                curFocusAction = Designer.FocusedObject as IActionRenderable;

            if (curFocusAction != null)
            {
                if (actionImplType == ActionTreeViewItemType.TokenCall)
                    curFocusAction.InnerAction.AddToken(actionImpl as TokenImpl);
                else if (actionImplType == ActionTreeViewItemType.FunctionCall)
                    curFocusAction.InnerAction.AddFunc(actionImpl as FunctionImpl);
                else
                    throw new Exception("Unbelievable type of action!!");
            }
            Designer.CurrentTool = new DefaultActionTool(Designer);
            Designer.FocusedObject = curFocusAction;
            curFocusAction = null;
            Designer.Cursor = Cursors.Default;
            Designer.Refresh();
        }

        public override void Render(Graphics g)
        {
            if (curFocusAction != null)
                curFocusAction.PaintFocus(g);
        }
    }
}
